package com.lrs.java.j2se_base.container;

import java.util.Collection;
import java.util.HashSet;

public class TestHashCodeAndEquals {
	public static void main(String[] args) {
		Collection c = new HashSet();
		c.add("hello");
		c.add("hello");
		c.add(new Person("f1", "l1"));
		c.add(new Person("f1", "l2"));
		c.add(new Person("f1", "l3"));
		c.add(new Person("f1", "l4"));

		System.out.println(c);

		System.out.println(new String("f1").hashCode() == new String("f1")
				.hashCode());
	}
}

class Person {

	public String firstName, lastName;

	public Person(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	@Override
	public String toString() {
		return firstName + " " + lastName;
	}

	@Override
	public boolean equals(Object obj) {
		System.out.println("equals.....");
		if (obj instanceof Person) {
			Person person = (Person) obj;
			return (firstName.equals(person.firstName))
					&& (lastName.equals(person.lastName));
		}
		return super.equals(obj);
	}

	@Override
	public int hashCode() {
		System.out.println("hashcode....");
		// System.out.println(firstName.hashCode());
		return firstName.hashCode();// 这个对象当作为索引的时候会使用
	}

}
